package com.linjiahao.nettyOne.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linjiahao.nettyOne.client.UserCenterClient;
import com.linjiahao.nettyOne.domain.ChatList;
import com.linjiahao.nettyOne.domain.ChatMessage;
import com.linjiahao.nettyOne.mapper.ChatListMapper;
import com.linjiahao.nettyOne.mapper.ChatMessageMapper;
import com.linjiahao.nettyOne.service.ChatMessageService;
import com.linjiahao.nettyOne.vo.ChatListVO;
import com.linjiahao.nettyOne.vo.ChatUserInfoVO;
import com.linjiahao.nettyOne.vo.MessageVO;
import com.linjiahao.servicebase.common.BaseConstant;
import com.linjiahao.servicebase.common.NettyMessageType;
import com.linjiahao.servicebase.common.ResultMap;
import com.linjiahao.servicebase.vo.NettyMessageVO;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
*
*/
@Service
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage> implements ChatMessageService{

    @Resource
    private UserCenterClient userCenterClient;

    @Resource
    private ChatListMapper chatListMapper;

    @Override
    public List<MessageVO> getHistoryMessage(Long userId, Long receiveId, Integer pageNo, Integer pageSize) {
        QueryWrapper<ChatMessage> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ChatMessage::getIsDelete, BaseConstant.Not_Pass).eq(ChatMessage::getMessageType, NettyMessageType.SINGLE_MESSAGE.getType())
                .and(queryWrapper ->
                queryWrapper.and(r-> r.eq(ChatMessage::getUserId,userId).eq(ChatMessage::getReceiveId,receiveId))
                        .or(q->q.and(y -> y.eq(ChatMessage::getUserId,receiveId).eq(ChatMessage::getReceiveId,userId))))
                .orderByDesc(ChatMessage::getUpdateTime);
        Page<ChatMessage> page = new Page(pageNo, pageSize);
        IPage<ChatMessage> iPage = this.baseMapper.selectPage(page, wrapper);
        List<MessageVO> list = new ArrayList<>();
        if(!CollectionUtils.isEmpty(iPage.getRecords())){
            List<Long> infoIds = Arrays.asList(userId, receiveId);
            ResultMap resultMap = userCenterClient.getUserInfoList(infoIds);
            List<ChatUserInfoVO> infoVOList = JSON.parseArray(JSON.toJSONString(resultMap.getData().get("list")), ChatUserInfoVO.class);
            Map<Long, ChatUserInfoVO> map = infoVOList.stream().collect(Collectors.toMap(ChatUserInfoVO::getUserId, a -> a));
            iPage.getRecords().stream().forEach(chatMessage -> {
                MessageVO messageVO = new MessageVO();
                messageVO.setUserId(chatMessage.getUserId());
                messageVO.setFriendId(chatMessage.getReceiveId());
                messageVO.setImg(map.get(chatMessage.getUserId()).getImg());
                messageVO.setMessageTime(chatMessage.getUpdateTime());
                messageVO.setMessageData(chatMessage.getMessageData());
                if(chatMessage.getUserId().equals(userId)){
                    messageVO.setSelf(Boolean.TRUE);
                }else {
                    messageVO.setSelf(Boolean.FALSE);
                }
                list.add(messageVO);
            });
        }
        return list;
    }

    @Override
    public NettyMessageVO addNewMessage(NettyMessageVO nettyMessageVO) {
        ChatMessage chatMessage = new ChatMessage();
        String messageId = UUID.randomUUID().toString();
        chatMessage.setMessageId(messageId);
        chatMessage.setUserId(nettyMessageVO.getUserId());
        chatMessage.setReceiveId(nettyMessageVO.getReceiveId());
        chatMessage.setMessageType(NettyMessageType.SINGLE_MESSAGE.getType());
        chatMessage.setMessageData(nettyMessageVO.getData());
        this.baseMapper.insert(chatMessage);

        nettyMessageVO.setMessageId(messageId);
        ChatListVO chatListVO = new ChatListVO();
        chatListVO.setUserId(nettyMessageVO.getUserId());
        chatListVO.setImg(nettyMessageVO.getImg());
        chatListVO.setMessage(nettyMessageVO.getData());
        chatListVO.setMessageType(NettyMessageType.SINGLE_MESSAGE.getType());
        chatListVO.setMessageTime(chatMessage.getUpdateTime());
        chatListVO.setNickName(nettyMessageVO.getNickName());
        nettyMessageVO.setData(JSON.toJSONString(chatListVO));
        //更新聊天列表最新消息id
        UpdateWrapper<ChatList> wrapper = new UpdateWrapper<>();
        wrapper.lambda().eq(ChatList::getUserId,nettyMessageVO.getUserId()).eq(ChatList::getFriendId,nettyMessageVO.getReceiveId());
        ChatList chatList = new ChatList();
        chatList.setMessageId(messageId);
        chatListMapper.update(chatList,wrapper);
        ChatList one = chatListMapper.selectOne(new QueryWrapper<ChatList>().lambda().eq(ChatList::getUserId, nettyMessageVO.getReceiveId())
                .eq(ChatList::getFriendId, nettyMessageVO.getUserId()).eq(ChatList::getIsDelete, BaseConstant.Not_Pass));
        if(one == null){
            ChatList add = new ChatList();
            add.setUserId(nettyMessageVO.getReceiveId());
            add.setFriendId(nettyMessageVO.getUserId());
            add.setMessageId(messageId);
            chatListMapper.insert(add);
        }else {
            chatList.setId(one.getId());
            chatListMapper.updateById(chatList);
        }
        return nettyMessageVO;
    }
}
